package main

import (
	"net"
	"fmt"
	"strings"
)

func HandleConn(conn net.Conn){
	defer conn.Close()

	//获取客户端信息
	addr := conn.RemoteAddr().String()
	fmt.Println(addr,"connect success")
	buf := make([]byte,2048)

	for{
		n,err := conn.Read(buf)
		if err != nil{
			fmt.Println("err=",err)
			return
		}

		fmt.Printf("[%s]:%s\n",addr,string(buf[:n]))
		fmt.Println("len=",len(string(buf[:n])))

		if "exit" == string(buf[0:n-1]){//\r\n
			fmt.Println(addr,"exit")
			return
		}

		conn.Write([]byte(strings.ToUpper(string(buf[:n]))))
	}

}


func main(){
	//监听
	listener,err := net.Listen("tcp","127.0.0.1:8000")
	if err != nil{
		fmt.Println("err=",err)
		return
	}
	defer listener.Close()
	//接收多个用户
	for {
		conn,err := listener.Accept()
		if err != nil{
			fmt.Println("err=",err)
			return
		}
		//处理用户请求，新建立一个协程
		go  HandleConn(conn)
	}
}